package com.fin.quant.app.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信验证码服务
 */
@Service
@Slf4j
public class SmsService {

    @Autowired
    //private RedisTemplate<String, String> redisTemplate;

    private static final String SMS_CODE_PREFIX = "sms:code:";
    private static final int CODE_LENGTH = 6;
    private static final int EXPIRE_MINUTES = 5; // 验证码5分钟过期

    /**
     * 发送短信验证码
     */
    public boolean sendVerifyCode(String phone, String countryCode) {
        try {
            // 生成6位数字验证码
            String verifyCode = generateVerifyCode();
            
            // 存储到Redis，5分钟过期
            String key = SMS_CODE_PREFIX + countryCode + phone;
            //redisTemplate.opsForValue().set(key, verifyCode, EXPIRE_MINUTES, TimeUnit.MINUTES);
            
            // 模拟发送短信（实际项目中应该调用短信服务商API）
            log.info("发送短信验证码到手机号: {} {}, 验证码: {}", countryCode, phone, verifyCode);
            
            // 这里默认返回成功，实际项目中应该根据短信服务商返回结果判断
            return true;
        } catch (Exception e) {
            log.error("发送短信验证码失败", e);
            return false;
        }
    }

    /**
     * 验证短信验证码
     */
    public boolean verifyCode(String phone, String countryCode, String inputCode) {
        try {
            String key = SMS_CODE_PREFIX + countryCode + phone;
            String storedCode = "";//redisTemplate.opsForValue().get(key);
            
            if (storedCode == null) {
                log.warn("验证码已过期或不存在: {}", phone);
                return false;
            }
            
            boolean isValid = storedCode.equals(inputCode);
            if (isValid) {
                // 验证成功后删除验证码
                //redisTemplate.delete(key);
                log.info("短信验证码验证成功: {}", phone);
            } else {
                log.warn("短信验证码验证失败: {}", phone);
            }
            
            return isValid;
        } catch (Exception e) {
            log.error("验证短信验证码失败", e);
            return false;
        }
    }

    /**
     * 生成验证码
     */
    private String generateVerifyCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 检查验证码是否存在（未过期）
     */
    public boolean hasValidCode(String phone, String countryCode) {
        try {
            String key = SMS_CODE_PREFIX + countryCode + phone;
            return true;//redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("检查验证码失败", e);
            return false;
        }
    }
}
